/*
 * @Description  : String
 * @Autor        : 杜康
 * @Date         : 2021-08-13 18:46:21 +0800
 * @LastEditors  : 杜康
 * @LastEditTime : 2021-08-14 13:48:04 +0800
 */

/**
 * @description: URL参数 转换 对象
 * @param { String } url 默认 url = window.location.href
 * @return { Object }
 * @author: 杜康
 * @Date: 2021-08-13 18:47:32 +0800
 */
const queryParseObject = (url) => {
    url = !url ? window.location.href : url;
    if (url.indexOf("?") === -1) {
        return {};
    }
    let search =
        url[0] === "?"
            ? url.substr(1)
            : url.substring(url.lastIndexOf("?") + 1);
    if (search === "") {
        return {};
    }
    search = search.split("&");
    let query = {};
    for (let i = 0; i < search.length; i++) {
        let pair = search[i].split("=");
        query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
    }
    return query;
};

/**
 * @description: 对象URL转换 &链接
 * @param { Object } obj
 * @return { String }
 * @author: 杜康
 * @Date: 2021-08-13 18:54:55 +0800
 */
const objectStringifyString = (obj) => {
    if (!obj) return "";
    let pairs = [];
    for (let key in obj) {
        let value = obj[key];
        if (value instanceof Array) {
            for (let i = 0; i < value.length; ++i) {
                pairs.push(
                    `${encodeURIComponent(`${key}[${i}]`)}=${encodeURIComponent(
                        value[i]
                    )}`
                );
            }
            continue;
        }
        pairs.push(
            `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
        );
    }
    return pairs.join("&");
};

/**
 * @description: URL协议转换 //xxx.ruiqikj.cn
 * @param { String } url
 * @return { String }
 * @author: 杜康
 * @Date: 2021-08-13 19:16:46 +0800
 */
const weakHttp = (url) => {
    if (!url) return "";
    return `//${url.split("//")[1]}`;
};

export default {
    queryParseObject,
    objectStringifyString,
    weakHttp,
};
